/**
 *    Copyright 2012 Geensoft S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
package ar.com.greensoft.neo.web.jsf.converters;

import java.io.Serializable;
import java.util.Locale;
import java.util.Map;
import java.util.WeakHashMap;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.hibernate.envers.RevisionType;

import ar.com.greensoft.neo.web.jsf.util.ResourceBundleUtil;

/**
 * @author Jorge E. Villaverde
 * @version 1.0.0
 * @since 16/01/2012	
 */
@FacesConverter(forClass=RevisionType.class, value="revisionTypeConverter")
public class RevisionTypeConverter implements Serializable, Converter{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static Map<RevisionType,String> typeResourceMap;
	
	static{
		typeResourceMap = new WeakHashMap<RevisionType, String>(RevisionType.values().length);
		for(RevisionType type : RevisionType.values()){
			StringBuilder builder = new StringBuilder();
			builder.append(type.getClass().getSimpleName());
			builder.append(".");
			builder.append(type.name());
			typeResourceMap.put(type, builder.toString());
		}
	}
	
	
	public static String getRevisionTypeString(RevisionType type, Locale locale){
		return ResourceBundleUtil.getResourceBundleString(typeResourceMap.get(type),locale);
	}
	
	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		Locale locale = context.getViewRoot().getLocale();
		for(RevisionType type : RevisionType.values()){
			if(getRevisionTypeString(type, locale).equals(value)){
				return type;
			}
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (context == null || component == null) {
            throw new NullPointerException();
        }

        // If the specified value is null, return a zero-length String
        if (value == null) {
            return "";
        }
    	RevisionType type = (RevisionType)value;
		Locale locale = context.getViewRoot().getLocale();
		return getRevisionTypeString(type, locale);
	}
}
